/**
 * 本模块封装了Android、iOS的应用权限判断、打开应用权限设置界面、以及位置系统服务是否开启
 */


var permissionSet = {
	location: {
		iOS: "location",
		Android: ['android.permission.ACCESS_FINE_LOCATION'],
		wx: "scope.userLocation",
		name: '定位权限'
	},
	camera: {
		iOS: "camera",
		Android: ['android.permission.CAMERA'],
		wx: "scope.camera",
		name: '摄像头权限'
	},
	photoLibrary: {
		iOS: "photoLibrary",
		Android: ['android.permission.READ_EXTERNAL_STORAGE', 'android.permission.WRITE_EXTERNAL_STORAGE'],
		name: '读写相机权限'
	},
	record: {
		iOS: "record",
		Android: ['android.permission.RECORD_AUDIO'],
		name: "麦克风权限"
	},
	phone: {
		iOS: "call",
		Android: ['android.permission.CALL_PHONE'],
		name: "拨打电话权限"
	}
}
var isIos
var runtimeDev
// #ifdef APP-PLUS
runtimeDev = plus.os.name
isIos = (runtimeDev == "iOS")
// #endif
function requestPermission(permission, content, title) {
	// #ifdef MP-WEIXIN
	return true
	// #endif
	if (uni.getStorageSync(permission + 'str')) {
		if (new Date().getTime() - uni.getStorageSync(permission + 'str') > 24 * 60 * 60 * 1000) {
			uni.showToast({
				title: '获取权限失败，请打开' + permissionSet[permission].name + '再使用',
				icon: 'none'
			});
			return;
		}
	}
	if (permission == 'location') {
		let result = checkSystemEnableLocation();
		if (!result) {
			uni.showModal({
				title: '提示',
				content: '请打开定位服务功能',
				showCancel: false,
				success() {
					var main = plus.android.runtimeMainActivity();
					var Intent = plus.android.importClass('android.content.Intent');
					var Settings = plus.android.importClass('android.provider.Settings');
					var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
					main.startActivity(intent); // 打开系统设置GPS服务页面
				}
			});
		} else {
			return getPermission(title)
		}
	} else {
		return getPermission(title)
	}

	function getPermission(title) {
		return new Promise(async (r, j) => {
			if (!permissionSet[permission]) {
				uni.showModal({
					content: "请确认申请的权限名称",
					showCancel: false
				})
				r(false)
			}
			// #ifdef H5
			r(true)
			return false
			// #endif
			if (!isIos) {
				// console.log(permissionSet[permission][runtimeDev])
				var result = await requestAndroidPermission(permissionSet[permission][runtimeDev], permission)
				switch (result) {
					case 1:
						// console.log('授权成功')
						r(true)
						break;
					case 0:
						// console.log('未获得授权')
						uni.showModal({
							content: content,
						});
						r(false)
						break;
					case -1:
						if (new Date().getTime() - uni.getStorageSync('locationstr') > 48 * 60 * 60 * 1000) {
							console.log('被永久拒绝权限')
							uni.showModal({
								title: title,
								content: content,
								// Text:'去授权',
								confirmText: '去授权',
								success: (res) => {
									if (res.confirm) {
										gotoAppPermissionSetting();
									}
								}
							});
						}
						r(false)
						break;
				}
			} else {
				console.log('获取标题', title)
				if (permissionSet[permission][runtimeDev]) {
					// r(true)
					var result = judgeIosPermission(permissionSet[permission][runtimeDev])
					if (!result) {
						uni.showModal({
							title: title,
							content: content,
							// Text:'去授权',
							confirmText: '去授权',
							success: (res) => {
								if (res.confirm) {
									gotoAppPermissionSetting()
								}
							}
						});
						// }
						result ? r(true) : r(false)

					} else {
						r(true)
					}
				} else {
					r(true)
				}
			}
		})
	}

	// permissionSet[permission].name

}

// 判断定位权限是否开启
function judgeIosPermissionLocation() {
	var result = false;
	var cllocationManger = plus.ios.import("CLLocationManager");
	var status = cllocationManger.authorizationStatus();
	console.log(status)
	result = (status != 2)
	console.log("定位权限开启：" + result);
	// 以下代码判断了手机设备的定位是否关闭，推荐另行使用方法 checkSystemEnableLocation
	/* var enable = cllocationManger.locationServicesEnabled();
	var status = cllocationManger.authorizationStatus();
	console.log("enable:" + enable);
	console.log("status:" + status);
	if (enable && status != 2) {
		result = true;
		console.log("手机定位服务已开启且已授予定位权限");
	} else {
		console.log("手机系统的定位没有打开或未给予定位权限");
	} */
	plus.ios.deleteObject(cllocationManger);
	return result;
}

// 判断麦克风权限是否开启
function judgeIosPermissionRecord() {
	var result = false;
	var avaudiosession = plus.ios.import("AVAudioSession");
	var avaudio = avaudiosession.sharedInstance();
	var permissionStatus = avaudio.recordPermission();
	console.log("permissionStatus:" + permissionStatus);
	if (permissionStatus == 1684369017 || permissionStatus == 1970168948) {
		console.log("麦克风权限没有开启");
	} else {
		result = true;
		console.log("麦克风权限已经开启");
	}
	plus.ios.deleteObject(avaudiosession);
	return result;
}

function iosCamera() {
	if (plus) {
		let result = 0,
			avCaptureDevice = plus.ios.importClass("AVCaptureDevice"),
			authStatus = avCaptureDevice.authorizationStatusForMediaType("vide");
		if (authStatus === 3) {
			result = 1;
		} else {
			result = 0;
		}
		plus.ios.deleteObject(avCaptureDevice);
		return result;
	} else {
		return null;
	}
}


// 判断相机权限是否开启
function judgeIosPermissionCamera() {
	// #ifdef APP-PLUS

	let result = false;
	// 利用 h5+ 方法
	var AVCaptureDevice = plus.ios.import("AVCaptureDevice");
	console.log('AVCaptureDevice', AVCaptureDevice)
	var authStatus = AVCaptureDevice.authorizationStatusForMediaType('vide');
	console.log("authStatus:" + authStatus);
	if (authStatus == 3) {
		result = true;
		console.log("相机权限已经开启");
	} else {
		console.log("相机权限没有开启");
		// 模拟扫码场景 获取相机权限
		let barcode = plus.barcode.create('barcode', [plus.barcode.QR], {
			top: '100px', //改为-9999px隐藏该页面
			left: '0',
			width: '100%',
			height: '500px',
			position: 'static'
		});
		plus.webview.currentWebview().append(barcode);
		// 
	}
	plus.ios.deleteObject(AVCaptureDevice);
	return result;

	// #endif
}

// 判断相册权限是否开启
function judgeIosPermissionPhotoLibrary() {
	var result = false;
	var PHPhotoLibrary = plus.ios.import("PHPhotoLibrary");
	var authStatus = PHPhotoLibrary.authorizationStatus();
	console.log("authStatus:" + authStatus);
	if (authStatus == 3) {
		result = true;
		console.log("相册权限已经开启");
		return result;
		// 0表示第一次授权
	} else if (authStatus == 0) {
		result = true;
		console.log("相册权限一次授权");
		return result;
	} else {
		console.log("相册权限没有开启");
		return result;
	}
	plus.ios.deleteObject(PHPhotoLibrary);

}

// 判断通讯录权限是否开启
function judgeIosPermissionContact() {
	var result = false;
	var CNContactStore = plus.ios.import("CNContactStore");
	var cnAuthStatus = CNContactStore.authorizationStatusForEntityType(0);
	if (cnAuthStatus == 3) {
		result = true;
		console.log("通讯录权限已经开启");
	} else {
		console.log("通讯录权限没有开启");
	}
	plus.ios.deleteObject(CNContactStore);
	return result;
}

// 判断日历权限是否开启
function judgeIosPermissionCalendar() {
	var result = false;
	var EKEventStore = plus.ios.import("EKEventStore");
	var ekAuthStatus = EKEventStore.authorizationStatusForEntityType(0);
	if (ekAuthStatus == 3) {
		result = true;
		console.log("日历权限已经开启");
	} else {
		console.log("日历权限没有开启");
	}
	plus.ios.deleteObject(EKEventStore);
	return result;
}

// 判断备忘录权限是否开启
function judgeIosPermissionMemo() {
	var result = false;
	var EKEventStore = plus.ios.import("EKEventStore");
	var ekAuthStatus = EKEventStore.authorizationStatusForEntityType(1);
	if (ekAuthStatus == 3) {
		result = true;
		console.log("备忘录权限已经开启");
	} else {
		console.log("备忘录权限没有开启");
	}
	plus.ios.deleteObject(EKEventStore);
	return result;
}

function setLocalStorge(name) {
	console.log(name)
	uni.setStorageSync(name + 'str', new Date().getTime());
}

function requestAndroidPermission(permissionID) {
	return new Promise((resolve, reject) => {
		plus.android.requestPermissions(
			[permissionID], // 理论上支持多个权限同时查询，但实际上本函数封装只处理了一个权限的情况。有需要的可自行扩展封装
			function(resultObj) {
				var result = 0;
				for (var i = 0; i < resultObj.granted.length; i++) {
					var grantedPermission = resultObj.granted[i];
					console.log('已获取的权限：' + grantedPermission);
					result = 1
				}
				for (var i = 0; i < resultObj.deniedPresent.length; i++) {
					var deniedPresentPermission = resultObj.deniedPresent[i];
					console.log('拒绝本次申请的权限：' + deniedPresentPermission);
					result = 0
				}
				for (var i = 0; i < resultObj.deniedAlways.length; i++) {
					var deniedAlwaysPermission = resultObj.deniedAlways[i];
					console.log('永久拒绝申请的权限：' + deniedAlwaysPermission);
					result = -1
				}
				resolve(result);
				// 若所需权限被拒绝,则打开APP设置界面,可以在APP设置界面打开相应权限
				// if (result != 1) {
				// gotoAppPermissionSetting()
				// }
			},
			function(error) {
				console.log('申请权限错误：' + error.code + " = " + error.message);
				resolve({
					code: error.code,
					message: error.message
				});
			}
		);
	});
}
// 使用一个方法，根据参数判断权限
function judgeIosPermission(permissionID) {
	if (permissionID == "location") {
		return judgeIosPermissionLocation()
	} else if (permissionID == "camera") {
		return judgeIosPermissionCamera()
	} else if (permissionID == "photoLibrary") {
		return judgeIosPermissionPhotoLibrary()
	} else if (permissionID == "record") {
		return judgeIosPermissionRecord()
	} else if (permissionID == "push") {
		return judgeIosPermissionPush()
	} else if (permissionID == "contact") {
		return judgeIosPermissionContact()
	} else if (permissionID == "calendar") {
		return judgeIosPermissionCalendar()
	} else if (permissionID == "memo") {
		return judgeIosPermissionMemo()
	}
	return false;
}

// 跳转到**应用**的权限页面
function gotoAppPermissionSetting() {
	if (isIos) {
		var UIApplication = plus.ios.import("UIApplication");
		var application2 = UIApplication.sharedApplication();
		var NSURL2 = plus.ios.import("NSURL");
		// var setting2 = NSURL2.URLWithString("prefs:root=LOCATION_SERVICES");		
		var setting2 = NSURL2.URLWithString("app-settings:");
		application2.openURL(setting2);

		plus.ios.deleteObject(setting2);
		plus.ios.deleteObject(NSURL2);
		plus.ios.deleteObject(application2);
	} else {
		var Intent = plus.android.importClass("android.content.Intent");
		var Settings = plus.android.importClass("android.provider.Settings");
		var Uri = plus.android.importClass("android.net.Uri");
		var mainActivity = plus.android.runtimeMainActivity();
		var intent = new Intent();
		// 'android.settings.APP_NOTIFICATION_SETTINGS'
		intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
		var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
		intent.setData(uri);
		mainActivity.startActivity(intent);
	}
}

// 检查系统的设备服务是否开启
// var checkSystemEnableLocation = async function () {
function checkSystemEnableLocation() {
	if (isIos) {
		var result = false;
		var cllocationManger = plus.ios.import("CLLocationManager");
		var result = cllocationManger.locationServicesEnabled();
		plus.ios.deleteObject(cllocationManger);
		return result;
	} else {
		var context = plus.android.importClass("android.content.Context");
		var locationManager = plus.android.importClass("android.location.LocationManager");
		var main = plus.android.runtimeMainActivity();
		var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
		var result = mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER);
		return result
	}
}

//手机权限，摄像头和图册
function phoneAuthority() {
	return new Promise(async (rel, rej) => {
		// 设备系统信息
		let systemInfomations = uni.getSystemInfoSync()
		var platform = systemInfomations.platform;
		if (platform == 'ios') {
			let camera = judgeIosPermission("camera"); //判断ios是否给予摄像头权限
			//ios相册没权限，系统会自动弹出授权框
			//let photoLibrary = permision.judgeIosPermission("photoLibrary");//判断ios是否给予相册权限
			if (camera) {
				console.log('苹果手机已经开启摄像头---相册权限')
				rel(true);
			} else {
				console.log('苹果手机需要开启摄像头--权限')
				rej(false);
			}
		} else {
			let camera = await permision.requestAndroidPermission("android.permission.CAMERA"); //判断安卓是否给予摄像头权限
			let photoLibrary = await permision.requestAndroidPermission(
				"android.permission.READ_EXTERNAL_STORAGE"); //判断安卓是否给予相册权限
			if (camera == 0 || photoLibrary == 0) {
				rej('请同时开启相机和相册的使用权限');
			} else if (camera == -1 || photoLibrary == -1) {
				//永久拒绝
				rej(false)
			} else {
				rel();
			}
		}
	})
}


module.exports = {
	judgeIosPermission: judgeIosPermission,
	requestAndroidPermission: requestAndroidPermission,
	checkSystemEnableLocation: checkSystemEnableLocation,
	gotoAppPermissionSetting: gotoAppPermissionSetting,
	requestPermission: requestPermission,
	phoneAuthority: phoneAuthority,
}